package com.csdj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csdj.exception.InsertException;
import com.csdj.exception.PasswordNotMatchException;
import com.csdj.exception.UserNotFoundException;
import com.csdj.exception.UsernameDuplicateException;
import com.csdj.pojo.TUser;
import com.csdj.mapper.TUserMapper;
import com.csdj.service.ITUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csdj.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 今晚几点睡Ada
 * @since 2022-09-07
 */
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements ITUserService {

    @Autowired
    private TUserMapper userMapper;
    @Override
    public void addUser(TUser user) {
        //判断用户名是否被注册
        TUser user1 = userMapper.selectOne(new QueryWrapper<TUser>().eq("username", user.getUsername()));
        //user1不为空 则用户名被占用 抛异常 为空则继续
        if (user1!=null){
            throw new UsernameDuplicateException("尝试注册的用户名[" + user.getUsername() + "]已经被占用");
        }
        //UUID盐值
        String salt = UUID.randomUUID().toString().toUpperCase();
        String Md5pwd= Md5Util.getMd5Password(user.getPassword(),salt);
        //补全数据  MP自动填充时间
        user.setSalt(salt);
        user.setPassword(Md5pwd);
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());

        //进行注册（添加用户）
        int insert = userMapper.insert(user);
        // 判断受影响的行数是否不为1
        if (insert != 1) {
            // 是：插入数据时出现某种错误，则抛出InsertException异常
            throw new InsertException("添加用户数据出现未知错误;");
        }

    }

    @Override
    public TUser toLogin(TUser user) {
        //判断用户名是否存在
        TUser user1 = userMapper.selectOne(new QueryWrapper<TUser>().eq("username", user.getUsername()));
        //user1为空 则用户名不存在 抛异常 不为空则继续
        if (user1==null){
            throw new UserNotFoundException("用户名[" + user.getUsername() + "]不存在");
        }
        //输入的密码
        String pwd=Md5Util.getMd5Password(user.getPassword(),user1.getSalt());
        //密码跟查到的对象中密码比较
        if (!pwd.equals(user1.getPassword())){
            //不相等则抛异常
            throw new PasswordNotMatchException("密码错误");
        }
        //将数据封装成新的对象，用于拦截和其他功能
        TUser LoginUser = new TUser();
        //id 用户名 头像
        LoginUser.setUid(user1.getUid());
        LoginUser.setUsername(user1.getUsername());
        LoginUser.setAvatar(user1.getAvatar());
        return LoginUser;
    }


}
